package com.example.demo.controller.admin;

import com.aliyun.oss.OSSClient;
import com.example.demo.config.OSSConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 富文本编辑器
 * @author vsalw
 */
@Controller
@RequestMapping("/admin")
public class FileXheditorController {

    public Logger log = LoggerFactory.getLogger(FileXheditorController.class);

    @RequestMapping("/upload")
    public String textArea() {
        return "textarea";
    }

    /**
     * 富文本编辑器 上传图片
     * @param file 文件数据
     * @return
     */
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    @ResponseBody
    public String imgUpload(@RequestBody MultipartFile file) {
        String filename = file.getOriginalFilename();
        if ("".equals(filename.trim())) {
            return "FileName is wrong!";
        }
        if (filename.length() > 20) {
            try {
                filename = System.currentTimeMillis() + "";
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String con = file.getContentType();
        //OSSClient上传到阿里云的工具类实例
        OSSClient client = OSSConfig.getOSSClient();
        String message;
        String err = "";
        String diskName = "datas/image/";
        String msgali = "http://vsalwtools.oss-cn-shanghai.aliyuncs.com/" + diskName + filename;
        try {
            OSSConfig.uploadObject2OSS(client, file.getInputStream(), filename, "vsalwtools", diskName, con);
        } catch (IOException e) {
            err = e.getMessage();
            e.printStackTrace();
        }
        log.info("上传后的文件地址:" + msgali);
        message = "{\"err\":\"" + err + "\",\"msg\":\"" + msgali
                + "\"}";
        return msgali;
    }

    /**
     * 富文本编辑器 接收前台编辑器传递的HTML代码
     * @param request
     */
    @RequestMapping("upload/textarea")
    @ResponseBody
    public void UploadContext(HttpServletRequest request) {
        ObjectMapper objectMapper = new ObjectMapper();
        //接受到的html代码
        Object object = request.getParameter("essaycontent");
        log.info("接收的HTML:" + object);
    }

}
